package com.example.luke.shengdangxiaoattendance.Util;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.example.luke.shengdangxiaoattendance.dhF9.dhF9Jni;

import com.example.luke.shengdangxiaoattendance.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.TimerTask;

/**
 * Created by yrdev on 9/6/16.
 */
public class MIReader {

    private Tag tag;

    private final static int NOPAPER = 3;
    private final static int LOWBATTERY = 4;
    private final static int PRINTVERSION = 5;
    private final static int PRINTBARCODE = 6;
    private final static int PRINTQRCODE = 7;
    private final static int PRINTPAPERWALK = 8;
    private final static int PRINTCONTENT = 9;
    private final static  int CANCELPROMPT = 10;
    private final static  int PRINTERR = 11;
    private final static int OVERHEAT = 12;
    private final static int MAKER = 13;
    private final static int PRINTPICTURE = 14;
    private final static int EXECUTECOMMAND = 15;
    private  boolean readStatus=true;//默认读卡成功
    private boolean write=false;

    private  int READ_SECTOR=10;

    public  interface Callback {

        void getCardInfo(Double reduceAmount, Double remain, Double currentBalance);
        void  getMICardNo(String cardNo, String ticketID);
        void showFixPurchaseCost(Double cost);

    }
    public  interface PrintListener{
        void printContent();

    }


    private Callback callback;

    String key="USER_PURCHASE_AMOUNT";
    private String data;
    private int operate ;//0读卡 1。写卡
   private MyHandler handler;
    private String oldCardID;
    private Boolean nopaper = false;
    private boolean LowBattery = false;
    private Context context;
    private ArrayList<MIReaderUtils.MIReaderObj> miReaderObjArrayList;
    private  int action=0;//0:充值，1:扣钱
    private  int paymentMode=1;//0：定额，1：随机
    private Integer reduceAmount=0;
    private final static int MAX_LEFT_DISTANCE = 255;
    private   int wordFont=2;
    private Integer prevBalance;
    private Integer minimumBalance;
    private String currentCardType;//当前卡类
    private Integer currentBalance;
     private String printContent="             烧烤" + "\n----------------------------" + "\n日期：2015-01-01 16:18:20" + "\n卡号：12378945664" + "\n单号：1001000000000529142" + "\n----------------------------"
            + "\n  项目    数量   单价  小计" + "\n秘制烤羊腿  1    56    56" + "\n黯然牛排    2    24    48" + "\n烤火鸡      2    50    100" + "\n炭烧鳗鱼    1    40    40" + "\n烤全羊      1    200   200"
            + "\n荔枝树烧鸡  1    50    50" + "\n冰镇乳鸽    2    23    46" + "\n秘制烤羊腿  1    56    56" + "\n黯然牛排    2    24    48" + "\n烤火鸡      2    50    100" + "\n炭烧鳗鱼    1    40    40"
            + "\n烤全羊      1    200   200" + "\n荔枝树烧鸡  1    50    50" + "\n冰镇乳鸽    2    23    46" + "\n秘制烤羊腿  1    56    56" + "\n黯然牛排    2    24    48" + "\n烤火鸡      2    50    100"
            + "\n炭烧鳗鱼    1    40    40" + "\n烤全羊      1    200   200" + "\n荔枝树烧鸡  1    50    50" + "\n冰镇乳鸽    2    23    46" + "\n秘制烤羊腿  1    56    56" + "\n黯然牛排    2    24    48"
            + "\n烤火鸡      2    50    100" + "\n炭烧鳗鱼    1    40    40" + "\n烤全羊      1    200   200" + "\n荔枝树烧鸡  1    50    50" + "\n冰镇乳鸽    2    23    46" + "\n冰镇乳鸽    2    23    46"
            + "\n秘制烤羊腿  1    56    56" + "\n黯然牛排    2    24    48" + "\n烤火鸡      2    50    100" + "\n炭烧鳗鱼    1    40    40" + "\n烤全羊      1    200   200" + "\n荔枝树烧鸡  1    50    50"
            + "\n冰镇乳鸽    2    23    46" + "\n 合计：1000：00元" + "\n----------------------------" + "\n本卡金额：10000.00" + "\n累计消费：1000.00" + "\n本卡结余：9000.00" + "\n----------------------------"
            + "\n 地址：广东省佛山市南海区桂城街道桂澜南路45号鹏瑞利广场A317.B-18号铺" + "\n欢迎您的再次光临\n";

    private  int purchaseMode=7;//1:充值,2:取款,3:退款,7:随机消费/定额消费,6:商品消费
    private  int leftDistance=0;


    private int lineDistance=0;

    private     int payMode=3;//0 现金,1 信用卡,2 签单,3 会员卡,4 礼劵, 8 - 退货  会员卡,9 - 退货  现金

    private String cardPassword;
    private String ticketID;
    private int printGray=5;
    public PrintListener printListener;

    public MIReader(Context context){
    this.context=context;
    }

    public void reset(){
        this.operate=0;
        this.action=0;

    }

    public void setMinimumBalance(Integer minimumBalance) {
        this.minimumBalance = minimumBalance;
    }


    public void setCallback(Callback callback) {

        this.callback = callback;
    }

    public void setREAD_SECTOR(int READ_SECTOR) {
        this.READ_SECTOR = READ_SECTOR;
    }

    public void setPrintListener(PrintListener printListener) {
        this.printListener = printListener;
    }

    public void setOldCardID(String oldCardID) {
        this.oldCardID = oldCardID;
    }

    public void setPaymentMode(int paymentMode) {
        this.paymentMode = paymentMode;
    }

    public void setReduceAmount(Integer reduceAmount) {


        this.reduceAmount = reduceAmount;


    }

    public void setOperate(int operate) {
        this.operate = operate;
    }

    public int getOperate() {
        return operate;
    }

    public void setAction(int action) {
        this.action = action;
    }

    public void setPurchaseMode(int purchaseMode) {
        this.purchaseMode = purchaseMode;
    }


    boolean showNominal=true;


    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
//            if (stop == true)
//                return;
            switch (msg.what) {
                case NOPAPER:
                  //  noPaperDlg();
                    break;
                case LOWBATTERY:
//                    AlertDialog.Builder alertDialog = new AlertDialog.Builder(PrinterActivity.this);
//                    alertDialog.setTitle(R.string.operation_result);
//                    alertDialog.setMessage(getString(R.string.LowBattery));
//                    alertDialog.setPositiveButton(getString(R.string.dlg_ok), new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialogInterface, int i) {
//                        }
//                    });
//                    alertDialog.show();
                    break;
                case PRINTVERSION:
//                    dialog.dismiss();
//                    if (msg.obj.equals("1")) {
//                        textPrintVersion.setText(printVersion);
//                    } else {
//                        Toast.makeText(PrinterActivity.this, R.string.operation_fail, Toast.LENGTH_LONG).show();
//                    }
                    break;
                case PRINTBARCODE:
                  //  new barcodePrintThread().start();
                    break;
                case PRINTQRCODE:
                 //   new qrcodePrintThread().start();
                    break;
                case PRINTPAPERWALK:
                  //  new paperWalkPrintThread().start();
                    break;
                case PRINTCONTENT:
                    new contentPrintThread().start();
                    break;
                case MAKER:
                   // new MakerThread().start();
                    break;
                case PRINTPICTURE:
                   // new printPicture().start();
                    break;
                case CANCELPROMPT:
//                    if (progressDialog != null && !PrinterActivity.this.isFinishing()) {
//                        progressDialog.dismiss();
//                        progressDialog = null;
//                    }
                    break;
                case EXECUTECOMMAND:
                    //new executeCommand().start();
                    break;
                case OVERHEAT:
//                    AlertDialog.Builder overHeatDialog = new AlertDialog.Builder(PrinterActivity.this);
//                    overHeatDialog.setTitle(R.string.operation_result);
//                    overHeatDialog.setMessage(getString(R.string.overTemp));
//                    overHeatDialog.setPositiveButton(getString(R.string.dlg_ok), new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialogInterface, int i) {
//                        }
//                    });
//                    overHeatDialog.show();
                    break;
                default:
                    Toast.makeText(context, "Print Error!", Toast.LENGTH_LONG).show();
                    break;
            }
        }
    }




    AlertDialog alertDialog;

    private String checkCardLength(String str, Integer length){
        int i=str.length();
        String temp="";
        while (i<length){
            temp=temp+"0";
            i++;

        }
        str=temp+str;

      return str;

    }

    public void  stopPrinter(){
       // ThermalPrinter.stop();

    }

    private void increaseCardIndex(Tag tag){//增加卡次数
        ticketID=GlobalFunction.getOnlyID(context);
        GlobalFunction.printTextByTag("insert card record");
        //    getBackUpIndex();
        int index=getBackUpIndex();
        String value= getMiCardValue(READ_SECTOR, index);
      Integer card_index= Integer.valueOf(MIReaderUtils.convertToDecimal1(value.substring(0, 4)));


        card_index=card_index+1;


        String temp= checkCardLength(MIReaderUtils.convertToHexString(card_index),4);

          String finalVal=value.replace(value.substring(0, 4), temp);


        write= writeTag(tag,finalVal,READ_SECTOR,getWriteBlock(index));

//        try {
//    cardRecord.setTicketID(ticketID);
//    String tempIndx= String.valueOf(card_index);
//    cardRecord.setUsageCount(Integer.valueOf(tempIndx));
//    cardRecord.setOperator(Operator.getIntance().getEmployeeID());
//    cardRecord.setCardName(getMIcardUserName());
//
//    DingHanDB.getInstance(context).insert(CardRecord.DH_TABLE_NAME,cardRecord);
//
//        }catch (Exception e){
//
//
//
//        }


    }

    private void  checkCardValidity(){//验证卡的状态
        String value=getMiCardValue(READ_SECTOR,2);
        if (value.length()==0){
            GlobalFunction.ToastAlert(context,"非常抱歉,非法卡");
            return;
        }
    }

    private void topUpCardAmount(Tag tag, Integer amount){//充值
    try {
        Integer index=getBackUpIndex();

        String value= getMiCardValue(READ_SECTOR, index);

        String oldCurrent=value.substring(8,14);

     Integer curAmount= Integer.valueOf(MIReaderUtils.convertToDecimal(value.substring(8,14)));


        prevBalance=  curAmount;

        currentBalance=  curAmount+amount;

        if (amount<=0){

            GlobalFunction.ToastAlert(context,"请输入充值余额");

        }else {

            String finalAmount= MIReaderUtils.convertToHexString((currentBalance));

//
            if (finalAmount.length()%2==1 || finalAmount.length()!=6)
            {
                finalAmount=   checkCardLength(finalAmount,6);

            }


//
            String finalValue=value.replace(oldCurrent, MIReaderUtils.convertHexPosition(finalAmount));

            replaceMIStoredValue(finalValue,READ_SECTOR,index);

//
//
           write=  writeTag(tag,finalValue,READ_SECTOR,getWriteBlock(index));
        //    GlobalFunction.printText("tag", status);
//
//            cardRecord =new CardRecord(getMICardNo());
//            cardRecord.setReportType(purchaseMode);
//           cardRecord.setPurchaseAmount(amount/100.);
//           cardRecord.setRemain(currentBalance/100.);
//
            increaseCardIndex(tag);
//

        }

//        }


    }catch (Exception e){
        GlobalFunction.printText("tag","error:"+e.getMessage());
    }
}
    private void reduceCardAmount(Tag tag, Integer amount){//扣钱
        try {
            Integer index=getBackUpIndex();

            String value= getMiCardValue(READ_SECTOR, index);

            String oldCurrent=value.substring(8,14);

            Integer curAmount= Integer.valueOf(MIReaderUtils.convertToDecimal(value.substring(8,14)));


            prevBalance=  curAmount;

            if (prevBalance<amount){

                GlobalFunction.ToastAlert(context,"非常抱歉，卡额不足");

            }else {
                currentBalance=  curAmount-amount;
                String finalAmount= MIReaderUtils.convertToHexString((currentBalance));

//
                if (finalAmount.length()%2==1 || finalAmount.length()!=6)
                {
                    finalAmount=   checkCardLength(finalAmount,6);

                }


//
                String finalValue=value.replace(oldCurrent, MIReaderUtils.convertHexPosition(finalAmount));

                replaceMIStoredValue(finalValue,READ_SECTOR,index);


                write=  writeTag(tag,finalValue,READ_SECTOR,getWriteBlock(index));
//                   cardRecord =new CardRecord(getMICardNo());
//                cardRecord.setReportType(purchaseMode);
//                cardRecord.setPurchaseAmount(amount/100.);
//                cardRecord.setRemain(currentBalance/100.);
//
                increaseCardIndex(tag);
//

            }





        }catch (Exception e){
            GlobalFunction.printText("tag","error:"+e.getMessage());
        }

}
    private  int getWriteBlock(Integer index){
        return READ_SECTOR*4+index;

    }



    private void showCardM1CardInfoContent(){//显示卡里信息
        getMICardNo();

    String[]strings={"卡号","类型","姓名","性别","卡余"};
    String content="查不到卡信息";
    String temp="";
    try {
        String[]values={getMICardNo(),getMICardType(),getMIcardUserName(),getMICardUserGender(),getMICardBalance()};
      for (int i=0;i<strings.length;i++){
          String key=strings[i];
          String val=values[i];
          temp=temp+key+" : "+val+"\n";
      }



    }catch (Exception e){
    GlobalFunction.printTextByTag("parse error");
    }

    if (temp !="")
        content=temp;

    showCardDialog(content);

}

    private void showCardDialog(String content){
    AlertDialog.Builder builder = new AlertDialog.Builder(context);

// 2. Chain together various setter methods to set the dialog characteristics
    builder.setMessage(content)
            .setTitle("M1卡信息");
    if (alertDialog==null){
        alertDialog=builder.create();
    }

    if (alertDialog.isShowing()){

        alertDialog.dismiss();
    }





    alertDialog.setMessage(content);
    alertDialog.show();
        startDismissDialog();


}
    private  void startDismissDialog(){//把弹窗过一时自动关闭
        new java.util.Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                alertDialog.dismiss();


                // GlobalFunction.ToastAlert(context,"ccasd");

            }

        }, 2000);
    }
   private String getMICardType(){//查看卡类
        String value="";

        try {
            value= getMiCardValue(READ_SECTOR, 2).substring(9,10);

        }
        catch (Exception e){

        }
        return value;

    }
    private String getMIcardUserName() throws IOException {//卡user
        String value="";

        try {
            value= getMiCardValue(READ_SECTOR+1,0).substring(0, 16);

        }
        catch (Exception e){

        }
        return MIReaderUtils.convertFromChinese(value);

    }

    private String getMICardNo(){//卡号
      String value="";
        GlobalFunction.printTextByTag(getMiCardValue(READ_SECTOR,2));
      try {

           value= getMiCardValue(READ_SECTOR, 2).substring(0, 4);
           String value2=getMiCardValue(READ_SECTOR, 2).substring(28, 30);
           value=value+value2;

            GlobalFunction.printTextByTag(value);
          //  GlobalFunction.printText("tag", value2);
      }
      catch (Exception e){
          GlobalFunction.printTextByTag(e.getMessage());
GlobalFunction.printTextByTag("read card no error");
      }
      return MIReaderUtils.convertToDecimal(value);


  }
    public void startPrintText(String printContent){//打印发票
        handler=new MyHandler();
        this.printContent=printContent;
        GlobalFunction.printTextByTag("start print");

        String exditText= String.valueOf(leftDistance);

     //   exditText = editTextLeftDistance.getText().toString();
        if (exditText == null || exditText.length() < 1) {
        //    Toast.makeText(context,context.getString(R.string.left_margin) + context.getString(R.string.lengthNotEnougth), Toast.LENGTH_LONG).show();
            return;
        }
        leftDistance = Integer.parseInt(exditText);
        exditText = String.valueOf(lineDistance);
        if (exditText == null || exditText.length() < 1) {
        //    Toast.makeText(context, context.getString(R.string.row_space) +context. getString(R.string.lengthNotEnougth), Toast.LENGTH_LONG).show();
            return;
        }
        lineDistance = Integer.parseInt(exditText);

        exditText = String.valueOf(wordFont);
        if (exditText == null || exditText.length() < 1) {
         //   Toast.makeText(context, context.getString(R.string.font_size) + context.getString(R.string.lengthNotEnougth), Toast.LENGTH_LONG).show();
            return;
        }
        wordFont = Integer.parseInt(exditText);
        exditText = String.valueOf(printGray);
        if (exditText == null || exditText.length() < 1) {
       //     Toast.makeText(context, context.getString(R.string.gray_level) + context.getString(R.string.lengthNotEnougth), Toast.LENGTH_LONG).show();
            return;
        }
        printGray = Integer.parseInt(exditText);
        if (leftDistance > MAX_LEFT_DISTANCE) {

        //    Toast.makeText(context, context.getString(R.string.outOfLeft), Toast.LENGTH_LONG).show();
            return;
        } else if (lineDistance > 255) {
        //    Toast.makeText(context, context.getString(R.string.outOfLine), Toast.LENGTH_LONG).show();
            return;
        } else if (wordFont > 4 || wordFont < 1) {
       //     Toast.makeText(context, context.getString(R.string.outOfFont), Toast.LENGTH_LONG).show();
            return;
        } else if (printGray < 0 || printGray > 12) {
       //     Toast.makeText(context, context.getString(R.string.outOfGray), Toast.LENGTH_LONG).show();
            return;
        }
        if (printContent == null || printContent.length() == 0) {
       //     Toast.makeText(context, context.getString(R.string.empty), Toast.LENGTH_LONG).show();
            return;
        }
        if (LowBattery == true) {

            handler.sendMessage(handler.obtainMessage(LOWBATTERY, 1, 0, null));

        } else {
            if (!nopaper) {
//                setTitle("print character");
//                progressDialog = ProgressDialog.show(PrinterActivity.this, getString(R.string.bl_dy), getString(R.string.printing_wait));
                handler.sendMessage(handler.obtainMessage(PRINTCONTENT, 1, 0, null));
            } else {
           //     Toast.makeText(context,context. getString(R.string.ptintInit), Toast.LENGTH_LONG).show();
            }
        }


    }
    private String getMICardUserGender(){//卡user性别
        String value="女";

        try {
            value= getMiCardValue(READ_SECTOR+1,0).substring(17, 11);
            int remark= Integer.valueOf(value);
            if (remark==1)
                value="男";
        }
        catch (Exception e){

        }

        return value;


    }
    private Integer getBackUpIndex(){
            Integer index=0;
            String value=getMiCardValue(READ_SECTOR,0).substring(0,4);
            String value2=getMiCardValue(READ_SECTOR,1).substring(0,4);

          Integer integer= Integer.valueOf(MIReaderUtils.convertToDecimal(value));
          Integer integer2= Integer.valueOf(MIReaderUtils.convertToDecimal(value2));
        if (integer>integer2){
            index=0;

        }else if(integer2>integer){
            index=1;

        }else {
            value= getMiCardValue(READ_SECTOR, 1).substring(8, 14);

            String temp=MIReaderUtils.convertToDecimal(value);
            Integer integer3= Integer.valueOf(temp);

            String value3=MIReaderUtils.convertToDecimal(getMiCardValue(READ_SECTOR, 0).substring(8, 14)) ;
            Integer integer1= Integer.valueOf(value3);

            if (integer1<integer3){
                index=0;

            }else {
                index=1;
            }
        }

        return index;

    }
    private String getMICardBalance(){//卡余额
        String value="";

        try {
            value= getMiCardValue(READ_SECTOR,getBackUpIndex()).substring(8, 14);

            String temp=MIReaderUtils.convertToDecimal(value);
            Integer integer= Integer.valueOf(temp);

                value= String.format("%.2f", integer / 100.);



        }
        catch (Exception e){

        }

        return value+"元";

    }


    private  void initCardData(){//从读卡的结果做初始化


        try {
            Integer index=getBackUpIndex();

            String value= getMiCardValue(READ_SECTOR, index);

            String oldCurrent=value.substring(8,14);

            Integer curAmount= Integer.valueOf(MIReaderUtils.convertToDecimal(value.substring(8,14)));
            currentBalance=curAmount;


            currentCardType=getMICardType();





        }catch (Exception e){
            GlobalFunction.printTextByTag(e.getMessage());
        }


    }



    public void processIntent(NfcAdapter mNfcAdapter, Intent intent) {//对卡进行操作
      GlobalFunction.printTextByTag("start process");
        readStatus=true;


      tag  = intent.getParcelableExtra(mNfcAdapter.EXTRA_TAG);
        String[] techList = tag.getTechList();
        byte[] ID = new byte[20];

        //data = tag.toString();
        ID = tag.getId();

        String password=MIReaderUtils.bytesToHexString(dhF9Jni.calculatePass(ID)).toUpperCase();
        cardPassword=password;



        data = "UID:\n" + MIReaderUtils. bytesToHexString(ID);
        data += "\n数据格式:";
        for (String tech : techList) {
            data += "\n" + tech;
        }
        data += "\n\n";
        if (operate == 0) // 读M1卡
        {
            data += readM1Tag(this.context,tag);
            showCardM1CardInfoContent();

            initCardData();



//            if (Setting.getInstance().checkCurrentCardType(currentCardType)){
//
//                if (readStatus)
//                    showCardM1CardInfoContent();
//
//            }else {
//
//              stopProcessCard();
//
//
//            }


        } else if (operate == 1) {  //先读卡后写卡
            data+= readM1Tag(this.context,tag);


            initCardData();

//            if (Setting.getInstance().checkCurrentCardType(currentCardType)){
//
//                if (readStatus)
//                    handleCorrespondAction();
//
//
//
//
//            }else {
//
//               stopProcessCard();
//
//            }


            //GlobalFunction.ToastAlert(context,"写卡成功");

            //data += writeTag(tag);
        }



    }

    private void stopProcessCard(){
        GlobalFunction.ToastAlert(context,"不是允许消费的卡类");


    }
    private  void  handleCorrespondAction(){



            switch(action){
                case 0: {

                    topUpCard();


                }
                break;
                case 1: {

//                    if (Setting.getInstance().checkCurrentProcessNominal(reduceAmount)){
//
//                        purchase();
//
//                    }else {
//
//                        GlobalFunction.ToastAlert(context,"高于单次最高消费金额");
//
//                    }

                }
                break;

            }




    }

    private void  topUpCard(){

        if (purchaseMode == 3) {//由于是退款,要先查看卡ID是否对应
            if (oldCardID.equals(getMICardNo())) {
                topUpCardAmount(tag, reduceAmount);


            } else {
                showNominal = false;
                GlobalFunction.ToastAlert(context, "非常抱歉,卡号不对应");
            }


        } else {

            topUpCardAmount(tag, reduceAmount);
        }
        startReadCard();

        //   if (write){//写卡成功
        if (callback!=null & showNominal){

            callback.getCardInfo(reduceAmount/100.,prevBalance/100.00,currentBalance/100.00);
            callback.getMICardNo(getMICardNo(),ticketID);

        }


    }
    private  void  purchase(){

        if (paymentMode==0)//如果是定额消费，先检查卡类找然后找对应卡类的扣款金额
        {
            //reduceAmount=FixPriceTimeSchedule.getInstance().getCurrentFixPrice(getMICardType());

            if (reduceAmount<=0){//不在营业时间范围
                {

                    GlobalFunction.ToastAlert(context,"未到刷卡时间");
                    return;

                }

            }else {


                if (callback!=null)
                {

                    callback.showFixPurchaseCost(reduceAmount/100.);
                }

            }

        }



        startPayment(); //如果消费模式是随机，进行直接扣费
        startReadCard();

        //   if (write){//写卡成功
        if (callback!=null & showNominal){

            callback.getCardInfo(reduceAmount/100.,prevBalance/100.00,currentBalance/100.00);
            callback.getMICardNo(getMICardNo(),ticketID);

        }

    }

    private void  startPayment(){
        int minBalance=minimumBalance+reduceAmount;

        if (currentBalance>minBalance){

            reduceCardAmount(tag, reduceAmount);

        }else {

            GlobalFunction.ToastAlert(context,"非常抱歉,余额不足");
        }
    }

    private void startReadCard(){//开始读卡
        //先清空然后重新读卡`
        miReaderObjArrayList.clear();
        readM1Tag(context,tag);
        initCardData();

    }


    private String readM1Tag(Context context, Tag tag) {

        MifareClassic mfc = MifareClassic.get(tag);
        miReaderObjArrayList=new ArrayList<>();

//        for (String tech : tag.getTechList()) {
//            System.out.println(tech);
//        }
        boolean auth = false;
        // 读取TAG

        try {
            GlobalFunction.printText("tag","read successs");
            String metaInfo = "";
            //Enable I/O operations to the tag from this TagTechnology object.
            mfc.connect();
            int type = mfc.getType();// 获取TAG的类型
            int sectorCount = mfc.getSectorCount();// 获取TAG中包含的扇区数
            String typeS = "";
            switch (type) {
                case MifareClassic.TYPE_CLASSIC:
                    typeS = "TYPE_CLASSIC";
                    break;
                case MifareClassic.TYPE_PLUS:
                    typeS = "TYPE_PLUS";
                    break;
                case MifareClassic.TYPE_PRO:
                    typeS = "TYPE_PRO";
                    break;
                case MifareClassic.TYPE_UNKNOWN:
                    typeS = "TYPE_UNKNOWN";
                    break;
            }
            metaInfo += "卡片类型：" + typeS + "\n共" + sectorCount + "个扇区\n共" + mfc.getBlockCount() + "个块\n存储空间: " + mfc.getSize()
                    + "B\n";
            for (int j = 0; j < sectorCount; j++) {
                //Authenticate a sector with key A.
                auth = mfc.authenticateSectorWithKeyA(j, MIReaderUtils.hexStringToByte(cardPassword));

                //if (j/6==0){
                    int bCount;
                    int bIndex;
                    if (auth) {
                        metaInfo += "Sector " + j + ":验证成功\n";
                        MIReaderUtils.MIReaderObj miReaderObj=new MIReaderUtils.MIReaderObj();
                        miReaderObj.setSector(j);

                        // 读取扇区中的块
                        bCount = mfc.getBlockCountInSector(j);
                        bIndex = mfc.sectorToBlock(j);
                        for (int i = 0; i < bCount; i++) {
                            byte[] data = mfc.readBlock(bIndex);

                            metaInfo += "Block " + bIndex + " : "
                                    + MIReaderUtils.bytesToHexString(data) + "\n";

                            miReaderObj.getBlock().add( MIReaderUtils.bytesToHexString(data));

                            bIndex++;
                        }

                        miReaderObjArrayList.add(miReaderObj);

                    } else {



                        metaInfo += "Sector " + j + ":验证失败\n";
                    }
               // }


            }

          //  GlobalFunction.printText("tag",metaInfo);
            checkCardValidity();//检查是否读到卡的信息

            return metaInfo;
        } catch (Exception e) {
            readStatus=false;
            GlobalFunction.printTextByTag(e.getMessage());
            GlobalFunction.ToastAlert(context, "Invalid card,Fail to read the card");
            //Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
            e.printStackTrace();
        } finally {
            if (mfc != null) {
                try {

                    mfc.close();

                } catch (IOException e) {

                    GlobalFunction.printTextByTag(e.getMessage());
                    GlobalFunction.ToastAlert(context, "Invalid card,Fail to read the card");
                 //   GlobalFunction.ToastAlert(context, e.getMessage());
                }
            }
        }
        return null;
    }


   private Boolean writeTag(Tag tag, String content, Integer sector, Integer tagBlock) {
       boolean stat=false;

        String metaInfo = "";
        String tempVal="0000000000000000000000000000B111";

         String tempContent=content;

        MifareClassic mfc = MifareClassic.get(tag);
    GlobalFunction.printTextByTag("write");
        try {
            mfc.connect();
            int sectorCount = mfc.getSectorCount();// 获取TAG中包含的扇区数
            boolean auth = false;
            int a=171;
            byte c=(byte)(a & 0xff );
            int k=0;
            ArrayList<String> arrayList=new ArrayList<>();

            while (k<tempContent.length()){

                String substring=tempContent.substring(k,k+2);

                arrayList.add(substring);

                k=k+2;
            }
            byte temp[] = {00,99,00,00,99,00,00,99,00,00,99,00,00,99,00,c};

            //GlobalFunction.printText("tag",String.valueOf(arrayList));
            for (int v=0;v<arrayList.size();v++){
                String string=arrayList.get(v);
                String converted_str= MIReaderUtils.convertToDecimal(string);
                int integer= Integer.valueOf(converted_str);
                if (integer>128){
                  temp[v]=(byte)(integer & 0xff);

                }else {
                    temp[v]=(byte)integer;
                }
            }




//            for(int k = 0; k < temp.length;k++ )
//            {
//                temp[k]= (byte) Integer.parseInt(tempContent);
//            }
//            short sectorAddress = 1;
//            //auth = mfc.authenticateSectorWithKeyA(sectorAddress, MifareClassic.KEY_NFC_FORUM);
//            auth = mfc.authenticateSectorWithKeyA(j, hexStringToByte(pwdData.getText().toString()));
//            if (auth) {
//                // the last block of the sector is used for KeyA and KeyB cannot be overwritted
//                mfc.writeBlock(4, "1313838438000000".getBytes());
//                mfc.writeBlock(5, "1322676888000000".getBytes());
//                mfc.close();
            // Toast.makeText(this, "写入成功", Toast.LENGTH_SHORT).show();
//            }

            for (int j = 0; j < sectorCount; j++) {
                if (j==sector){
                    //Authenticate a sector with key A.
                    auth = mfc.authenticateSectorWithKeyA(j, MIReaderUtils.hexStringToByte(cardPassword));
                    int bCount;
                    int bIndex;
                    if (auth) {

                        metaInfo += "Sector " + j + ":验证成功\n";
                        // 读取扇区中的块
                        bCount = mfc.getBlockCountInSector(j);
                        bIndex = mfc.sectorToBlock(j);
                        for (int i = 0; i < bCount; i++) {
                            int block = 4*j+i;
                            if ( block == 0 || block%4 == 3){
                                continue;
                            }
                            GlobalFunction.printTextByTag("block:"+block+":"+tagBlock);
//                            GlobalFunction.printTextByTag("auth1"+auth);
                            if (block==tagBlock)
                            {
                                GlobalFunction.printTextByTag("auth"+auth);
                                //     GlobalFunction.printText("tag","write");
                                mfc.writeBlock(block, temp);
                                stat=true;

                            }

                            bIndex++;
                        }
                    } else {
                        metaInfo += "Sector " + j + ":验证失败\n";
                    }

                }

            }
        } catch (IOException e) {
            GlobalFunction.printTextByTag(e.getMessage());
            GlobalFunction.ToastAlert(context,"刷卡失败");
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                mfc.close();
            } catch (IOException e) {
                GlobalFunction.ToastAlert(context,"刷卡失败");
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return stat;

    }


private void replaceMIStoredValue(String value, Integer sector, Integer block){

     try {

        MIReaderUtils.MIReaderObj obj=miReaderObjArrayList.get(sector);


         if (obj.getSector().equals(sector))
             obj.getBlock().set(block,value);

         //    value= String.valueOf(obj.getBlock().get(block));




     }catch (Exception e){

     }
 }

    private String getMiCardValue(Integer sector, Integer block){


      String value="";
try {

    for (MIReaderUtils.MIReaderObj obj : miReaderObjArrayList){

        if (obj.getSector().equals(sector)){

            value= String.valueOf(obj.getBlock().get(block));
        }

    }
  //  MIReaderUtils.MIReaderObj obj=miReaderObjArrayList.get(sector);







}catch (Exception e){

}
      return value;

  }
    private class contentPrintThread extends Thread {
        @Override
        public void run() {
            super.run();
            setName("Content Print Thread");
            try {

//                ThermalPrinter.start(context);
//                ThermalPrinter.reset();
//                ThermalPrinter.setAlgin(ThermalPrinter.ALGIN_LEFT);
//                ThermalPrinter.setLeftIndent(leftDistance);
//                ThermalPrinter.setLineSpace(lineDistance);
//                if (wordFont == 4) {
//                    ThermalPrinter.setFontSize(2);
//                    ThermalPrinter.enlargeFontSize(2, 2);
//                } else if (wordFont == 3) {
//                    ThermalPrinter.setFontSize(1);
//                    ThermalPrinter.enlargeFontSize(2, 2);
//                } else if (wordFont == 2) {
//                    ThermalPrinter.setFontSize(2);
//                } else if (wordFont == 1) {
//                    ThermalPrinter.setFontSize(1);
//                }
//                ThermalPrinter.setGray(printGray);
//                ThermalPrinter.addString(printContent);
//                ThermalPrinter.printString();
//                ThermalPrinter.clearString();
//                ThermalPrinter.walkPaper(100);

            } catch (Exception e) {
                e.printStackTrace();
//                Result = e.toString();
//                if (Result.equals("com.telpo.tps550.api.printer.NoPaperException")) {
//                    nopaper = true;
//                } else if (Result.equals("com.telpo.tps550.api.printer.OverHeatException")) {
//                    handler.sendMessage(handler.obtainMessage(OVERHEAT, 1, 0, null));
//                } else {
//                    handler.sendMessage(handler.obtainMessage(PRINTERR, 1, 0, null));
//                }
            } finally {
//                handler.sendMessage(handler.obtainMessage(CANCELPROMPT, 1, 0, null));
//                if (nopaper){
//                    handler.sendMessage(handler.obtainMessage(NOPAPER, 1, 0, null));
//                    nopaper = false;
//                    return;
//                }
//                ThermalPrinter.stop(context);
//                Log.v(TAG, "The Print Progress End !!!");
//                if (isClose) {
//                    finish();
//                }
            }
        }
    }





}
